package br.com.ViewPRE_VENDA;

import br.com.controler.DavCabecalhoControler;
import br.com.controler.PreVendaCabecalhoControler;
import br.com.controler.PreVendaDetalheControler;
import br.com.modelo.DavCabecalho;
import br.com.modelo.PreVendaCabecalho;
import br.com.modelo.PreVendaDetalhe;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import util.Relatorios;

/**
 *
 * @author Administrador
 */
public class Pre_Vendas_Aberto extends javax.swing.JDialog {

    List<PreVendaCabecalho> ListPrevendas = new ArrayList<>();
    List<PreVendaDetalhe> ListItensPrevenda = new ArrayList<>();
    //variaveis de controle
    DateFormat dateForm = new SimpleDateFormat("dd/MM/yyyy");
    NumberFormat decimal = NumberFormat.getCurrencyInstance();
    public static Boolean altera = false;

    public Pre_Vendas_Aberto(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        ListPrevendas = PreVendaCabecalhoControler.retornaPreVendaEmAberto();
        adicionaProdutoNaTabela();

        CancelaAction cancelaAction = new CancelaAction();
        btCancela.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancelaAction");
        btCancela.getActionMap().put("cancelaAction", cancelaAction);

        ReimprimeDavAction reimprimeAction = new ReimprimeDavAction();
        btCancela.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), "reimprimeAction");
        btCancela.getActionMap().put("reimprimeAction", reimprimeAction);

        alteraDavAction alteraAction = new alteraDavAction();
        btAlteraDAV.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), "altetraAction");
        btAlteraDAV.getActionMap().put("altetraAction", alteraAction);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableDavCabecalho = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableItens = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        btCancela = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        btAlteraDAV = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "Pre-Vendas em Aberto"));

        tableDavCabecalho.setAutoCreateRowSorter(true);
        tableDavCabecalho.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Nº DAV", "Cliente", "Data Emissão", "Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableDavCabecalho.setRowHeight(20);
        tableDavCabecalho.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableDavCabecalho.getTableHeader().setReorderingAllowed(false);
        tableDavCabecalho.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableDavCabecalhoMouseClicked(evt);
            }
        });
        tableDavCabecalho.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tableDavCabecalhoKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(tableDavCabecalho);
        tableDavCabecalho.getColumnModel().getColumn(0).setHeaderValue("ID");
        tableDavCabecalho.getColumnModel().getColumn(1).setMinWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(1).setPreferredWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(1).setMaxWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(1).setHeaderValue("Nº DAV");
        tableDavCabecalho.getColumnModel().getColumn(2).setMinWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(2).setPreferredWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(2).setMaxWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(2).setHeaderValue("Cliente");
        tableDavCabecalho.getColumnModel().getColumn(3).setMinWidth(100);
        tableDavCabecalho.getColumnModel().getColumn(3).setPreferredWidth(100);
        tableDavCabecalho.getColumnModel().getColumn(3).setMaxWidth(100);
        tableDavCabecalho.getColumnModel().getColumn(3).setHeaderValue("Data Emissão");
        tableDavCabecalho.getColumnModel().getColumn(4).setMinWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(4).setPreferredWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(4).setMaxWidth(80);
        tableDavCabecalho.getColumnModel().getColumn(4).setHeaderValue("Valor");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 179, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 700, 200));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true), "Itens d a Pré-Venda"));

        tableItens.setAutoCreateRowSorter(true);
        tableItens.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Produto", "Unidade", "Qtde", "Vlr.Unitário", "Vlr.Total"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableItens.setRowHeight(20);
        tableItens.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableItens.getTableHeader().setReorderingAllowed(false);
        jScrollPane2.setViewportView(tableItens);
        tableItens.getColumnModel().getColumn(0).setHeaderValue("ID");
        tableItens.getColumnModel().getColumn(1).setMinWidth(80);
        tableItens.getColumnModel().getColumn(1).setPreferredWidth(80);
        tableItens.getColumnModel().getColumn(1).setMaxWidth(80);
        tableItens.getColumnModel().getColumn(1).setHeaderValue("Valor");
        tableItens.getColumnModel().getColumn(2).setMinWidth(80);
        tableItens.getColumnModel().getColumn(2).setPreferredWidth(80);
        tableItens.getColumnModel().getColumn(2).setMaxWidth(80);
        tableItens.getColumnModel().getColumn(2).setHeaderValue("Nº DAV");
        tableItens.getColumnModel().getColumn(3).setMinWidth(80);
        tableItens.getColumnModel().getColumn(3).setPreferredWidth(80);
        tableItens.getColumnModel().getColumn(3).setMaxWidth(80);
        tableItens.getColumnModel().getColumn(3).setHeaderValue("Cliente");
        tableItens.getColumnModel().getColumn(4).setMinWidth(100);
        tableItens.getColumnModel().getColumn(4).setPreferredWidth(100);
        tableItens.getColumnModel().getColumn(4).setMaxWidth(100);
        tableItens.getColumnModel().getColumn(4).setHeaderValue("Data Emissão");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 690, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 189, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 220, -1, 210));

        jButton1.setText("Cancelar Pré-Venda Selecionado (F4)");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 460, 240, -1));

        btCancela.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imgBotoes/botaoCancelar.png"))); // NOI18N
        btCancela.setText("Fechar Janela (ESC)");
        btCancela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelaActionPerformed(evt);
            }
        });
        getContentPane().add(btCancela, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 460, 170, -1));

        jButton2.setText("Reimprimir (F3)");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 460, 140, -1));

        btAlteraDAV.setText("Alterar (F12)");
        btAlteraDAV.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlteraDAVActionPerformed(evt);
            }
        });
        getContentPane().add(btAlteraDAV, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 460, 130, -1));

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-708)/2, (screenSize.height-534)/2, 708, 534);
    }// </editor-fold>//GEN-END:initComponents

    private void tableDavCabecalhoKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableDavCabecalhoKeyReleased
        if (evt.getKeyCode() == KeyEvent.VK_DOWN || evt.getKeyCode() == KeyEvent.VK_UP) {
            getItensDav();
        }
    }//GEN-LAST:event_tableDavCabecalhoKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        CancelaDAV();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void tableDavCabecalhoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableDavCabecalhoMouseClicked
        getItensDav();
    }//GEN-LAST:event_tableDavCabecalhoMouseClicked

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        reimprimeDav();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btCancelaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelaActionPerformed
        dispose();
    }//GEN-LAST:event_btCancelaActionPerformed

    private void btAlteraDAVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlteraDAVActionPerformed
        altera = true;
        dispose();
    }//GEN-LAST:event_btAlteraDAVActionPerformed

    public static void main(String args[]) {
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Pre_Vendas_Aberto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Pre_Vendas_Aberto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Pre_Vendas_Aberto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Pre_Vendas_Aberto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                Pre_Vendas_Aberto dialog = new Pre_Vendas_Aberto(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlteraDAV;
    private javax.swing.JButton btCancela;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tableDavCabecalho;
    private javax.swing.JTable tableItens;
    // End of variables declaration//GEN-END:variables

    private void adicionaProdutoNaTabela() {
        DefaultTableModel modelo = (DefaultTableModel) tableDavCabecalho.getModel();
        DefaultTableModel tblRemove = (DefaultTableModel) tableDavCabecalho.getModel();
        while (tableDavCabecalho.getRowCount() > 0) {
            tblRemove.removeRow(0);
        }
        if (!ListPrevendas.isEmpty()) {
            for (PreVendaCabecalho prod : ListPrevendas) {
                modelo.addRow(new String[]{
                            prod.getId().toString(),
                            prod.getSituacao().toString(),
                            prod.getValor().toString(),
                            dateForm.format(prod.getDataPv()),
                            decimal.format(prod.getValor())});
            }
        }
    }

    private void populaTabelaItensDav() {
        DefaultTableModel modelo = (DefaultTableModel) tableItens.getModel();
        DefaultTableModel tblRemove = (DefaultTableModel) tableItens.getModel();
        while (tableItens.getRowCount() > 0) {
            tblRemove.removeRow(0);
        }
        if (!ListItensPrevenda.isEmpty()) {
            for (PreVendaDetalhe prod : ListItensPrevenda) {
                modelo.addRow(new String[]{
                            prod.getIdProduto().getDescricao(),
                            prod.getIdProduto().getIdUnidadeProduto().getNome(),
                            prod.getQuantidade().toString(),
                            decimal.format(prod.getValorUnitario()),
                            decimal.format(prod.getValorTotal())});
            }
        }
    }

    private void getItensDav() {
        if (tableDavCabecalho.getSelectedRow() != -1) {
            //pegando o ID do dav selecionado na tabela 
            AbstractTableModel modelo = (AbstractTableModel) tableDavCabecalho.getModel();
            String idDAV = ((String) modelo.getValueAt(tableDavCabecalho.getSelectedRow(), 0));
            //retornando os Itens do DAV
            ListItensPrevenda = PreVendaDetalheControler.retornaPreVendaEmAberto(Integer.parseInt(idDAV));
            populaTabelaItensDav();
        }
    }

    private void CancelaDAV() {
        if (tableDavCabecalho.getSelectedRow() != -1) {
            String[] opcoes = {"Sim", "Não"};
            int escolha = JOptionPane.showOptionDialog(null, "Confirma cancelar o DAV Selecionado?", "Pergunta do Sistema",
                    JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE,
                    null, opcoes, null);
            if (escolha == JOptionPane.YES_OPTION) {

                //pegando o ID do dav selecionado na tabela 
                AbstractTableModel modelo = (AbstractTableModel) tableDavCabecalho.getModel();
                String idDAV = ((String) modelo.getValueAt(tableDavCabecalho.getSelectedRow(), 0));
                DavCabecalho dav = DavCabecalhoControler.retornaDavPorId(Integer.parseInt(idDAV));
                if (dav != null) {
                    dav.setSituacao('C');//marca como cancelado
                    dav = dav.salvar();
                    ListPrevendas = PreVendaCabecalhoControler.retornaPreVendaEmAberto();
                    adicionaProdutoNaTabela();

                    //exclui linhas da tabela de itens de dav
                    DefaultTableModel tblRemove = (DefaultTableModel) tableItens.getModel();
                    while (tableItens.getRowCount() > 0) {
                        tblRemove.removeRow(0);
                    }
                }
            }
        } else {
            JOptionPane.showMessageDialog(null, "Nenhum DAV selecionado para Cancelamento!!", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
        }
    }

    private class CancelaAction extends AbstractAction {

        public CancelaAction() {
        }

        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    }

    private class ReimprimeDavAction extends AbstractAction {

        public ReimprimeDavAction() {
        }

        public void actionPerformed(ActionEvent e) {
            reimprimeDav();
        }
    }

    private class alteraDavAction extends AbstractAction {

        public alteraDavAction() {
        }

        public void actionPerformed(ActionEvent e) {
            altera = true;
            dispose();
        }
    }

    private void reimprimeDav() {
        if (tableDavCabecalho.getSelectedRow() != -1) {
            String[] opcoes = {"Sim", "Não"};
            int escolha = JOptionPane.showOptionDialog(null, "Confirma reimpressão do DAV Selecionado?", "Pergunta do Sistema",
                    JOptionPane.YES_OPTION, JOptionPane.QUESTION_MESSAGE,
                    null, opcoes, null);
            if (escolha == JOptionPane.YES_OPTION) {
                //pegando o ID do dav selecionado na tabela 
                AbstractTableModel modelo = (AbstractTableModel) tableDavCabecalho.getModel();
                String idDAV = ((String) modelo.getValueAt(tableDavCabecalho.getSelectedRow(), 0));
                Relatorios.geraRelatorioDAV("imprimir", Integer.parseInt(idDAV));
            }
        } else {
            JOptionPane.showMessageDialog(null, "Nenhum DAV selecionado para Cancelamento!!", "Mensagem do sistema", JOptionPane.ERROR_MESSAGE);
        }
    }

    public PreVendaCabecalho getPreVenda() {
        AbstractTableModel modelo = (AbstractTableModel) tableDavCabecalho.getModel();
        String idDAV = ((String) modelo.getValueAt(tableDavCabecalho.getSelectedRow(), 0));
        PreVendaCabecalho davCab = PreVendaCabecalhoControler.retornaPreVendaPorId(Integer.parseInt(idDAV));
        return davCab;
    }
}
